package frontend.pages.worklog.daily;

import backend.model.worklog.WorkLog;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDataProvider;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;

import java.util.*;

public class WorkLogTable extends DefaultDataTable<WorkLog> {

    private List<WorkLog> workLogList = new ArrayList<WorkLog>();

    public WorkLogTable(String id, List<WorkLog> workLogList, DefaultWorkLogTableTemplate tableTemplate) {
        super(id, tableTemplate.getColumns(), getDataProvider(workLogList), 20);
        this.workLogList = workLogList;
    }

    public static ISortableDataProvider<WorkLog> getDataProvider(final List<WorkLog> list) {
        // Default sort by date
        sortData(list, new SortParam("date", true));

        ISortableDataProvider<WorkLog> dataProvider = new SortableDataProvider<WorkLog>() {
            @Override
            public Iterator<? extends WorkLog> iterator(int first, int count) {
                sortData(list, getSort());
                return list.subList(first, first+count).iterator();
            }

            @Override
            public int size() {
                return list.size();
            }

            @Override
            public IModel<WorkLog> model(final WorkLog workLog) {
                return new LoadableDetachableModel<WorkLog>() {
                    @Override
                    protected WorkLog load() {
                        return workLog;
                    }
                };
            }
        };
        return dataProvider;
    }

    public boolean isVisible() {
        return this.workLogList.size() > 0;
    }

    public static void sortData(List<WorkLog> list, SortParam sortParam) {
        if (sortParam != null) {
            Comparator<WorkLog> comparator = DefaultWorkLogTableTemplate.comparatorMap.get(sortParam.getProperty());
            if (comparator != null) {
                Collections.sort(list, comparator);
                if (!sortParam.isAscending()) {
                    Collections.reverse(list);
                }
            }
        }
    }
}
